import chargeStationIcon from '@/assets/png/chongdianzhan.png';
import AMap from '@/components/AMap';
import QueryForm from '@/components/QueryForm';
import { STATE_OPTIONS } from '@/constants/enums';
import request from '@/utils/request';
import { Checkbox, Select } from 'antd';
import { useEffect, useRef, useState } from 'react';
import styles from './index.less';

export default (props) => {
  const { searchUrl, searchFields, type, markerImage, nameField } = props;
  const map = useRef();
  const [data, setData] = useState([]);
  const [isShowArea, setIsShowArea] = useState(true);
  const areaObj = useRef([]);

  const fields = [
    {
      label: '充电站名称',
      name: 'chargeStationName',
    },
    {
      label: '状态',
      name: 'state',
      children: (
        <Select allowClear placeholder="请选择" options={STATE_OPTIONS} />
      ),
    },
  ];
  useEffect(() => {
    (async () => {
      map.current = new AMap({
        domId: 'charge_station_map',
      });
      await map.current.load();
      handleSearch();
    })();

    return () => {
      map.current.destroy();
    };
  }, []);
  const showArea = () => {};
  useEffect(() => {
    areaObj.current = [];
    if (data.length) {
      for (let i = 0; i < data.length; i++) {
        map.current.loadLabelMarker({
          lat: data[i].lat,
          lng: data[i].lng,
          title: data[i].chargeStationName,
          image: chargeStationIcon,
          showInfoWindow: true,
          infoWindowContent: `<div class="marker-info-name">${
            data[i].chargeStationName
          }</div><div class="marker-info-container">
              <div class="info-item">
                <div class="title">状态:</div>
                <div class="content">${
                  STATE_OPTIONS.find((item) => item.value === data[i].state)
                    ?.label
                }</div>
              </div>
              <div class="info-item">
                <div class="title">设备数量:</div>
                <div class="content" title="${data[i].total}">${
            data[i].total
          }</div>
              </div>
              <div class="info-item">
                <div class="title">充电:</div>
                <div class="content">${
                  data[i].charging === 1 ? '支持' : '不支持'
                }</div>
              </div>
              <div class="info-item">
                <div class="title">换电:</div>
                <div class="content">${
                  data[i].changing === 1 ? '支持' : '不支持'
                }</div>
              </div>
              <div class="info-item">
                <div class="title">交接:</div>
                <div class="content">${
                  data[i].joining === 1 ? '支持' : '不支持'
                }</div>
              </div>
              <div class="info-item">
                <div class="title">服务费:</div>
                <div class="content" title="${data[i].servicePrice}">${
            data[i].servicePrice
          }</div>
              </div>
              <div class="info-item">
                <div class="title">地址:</div>
                <div class="content" title="${data[i].address}">${
            data[i].address
          }</div>
              </div>
              <div class="info-item">
                <div class="title">联系人:</div>
                <div class="content" title="${data[i].contacts}">${
            data[i].contacts
          }</div>
              </div>
              <div class="info-item">
                <div class="title">电话:</div>
                <div class="content" title="${data[i].phone}">${
            data[i].phone
          }</div>
              </div>
              <div class="info-item">
                <div class="title">当前坐标:</div>
                <div class="content" title="${data[i].lat},${data[i].lng}">${
            data[i].lat
          },${data[i].lng}</div>
              </div>
              <div class="info-item">
                <div class="title">面积:</div>
                <div class="content" title="${data[i].area}平方公里">${
            data[i].area
          }平方公里</div>
              </div>
            </div>`,
        });
        if (isShowArea && data[i].points) {
          const path = data[i].points?.split(';').map((item) => {
            const lngLat = item.split(',');
            return { lat: lngLat[1], lng: lngLat[0] };
          });
          // 加载区域
          const polygon = map.current.loadPolygon(path, true);
          areaObj.current.push(polygon);
        }
      }
    }
  }, [data]);
  useEffect(() => {
    if (isShowArea) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].points) {
          const path = data[i].points.split(';').map((item) => {
            const lngLat = item.split(',');
            return { lat: lngLat[1], lng: lngLat[0] };
          });
          // 加载区域
          const polygon = map.current.loadPolygon(path, true);
          areaObj.current.push(polygon);
        }
      }
    } else {
      for (let i = 0; i < areaObj.current.length; i++) {
        map.current.remove(areaObj.current[i]);
      }
      areaObj.current = [];
    }
  }, [isShowArea]);
  const queryFormProps = { labelCol: 7 };
  const handleSearch = async (params) => {
    // 先清空地图上的所有覆盖物
    map.current.clear();
    const res = await request({
      url: '/datas/charge/station/list',
      method: 'GET',
      custom: true,
      params: {
        ...params,
        index: 0,
        size: 0,
      },
    });
    setData(res.data);
  };
  const onChange = (e) => {
    setIsShowArea(e.target.checked);
  };

  return (
    <div className={styles['map-viewer']}>
      <header className={styles['map-viewer-header']}>
        <QueryForm
          fields={fields}
          {...queryFormProps}
          onSearch={handleSearch}
        />
      </header>
      <div className={styles['map-viewer-toolbar']}>
        <Checkbox defaultChecked onChange={onChange}>
          显示区域
        </Checkbox>
      </div>
      <div className={styles['map-viewer-content']}>
        <div className={styles['map-viewer-map']} id="charge_station_map"></div>
      </div>
    </div>
  );
};
